package org.jeecg.modules.commodity.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.log4j.Log4j2;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.commodity.entity.Commodity;
import org.jeecg.modules.commodity.model.CommodityModel;
import org.jeecg.modules.commodity.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: zhuzhuhong
 * @Date: 2019/11/12 16:18
 * @Description:
 */
@Log4j2
@RestController
@RequestMapping(value = "/commodity/commodity")
public class CommodityController {

    @Autowired
    private CommodityService commodityService;

    @GetMapping(value = "/list")
    public Result<IPage<CommodityModel>> getCommodityModel(
            @RequestParam(value = "pageNo",required = false) Integer pageNo,
            @RequestParam(value = "pageSize",required = false) Integer pageSize,
            @RequestParam(value = "commodityName",required = false) String commodityName
    ){
        Result<IPage<CommodityModel>> pageResult = new Result<>();
        try {
            List<CommodityModel> list = commodityService.findCommodityModelByCommodityName(commodityName);
            if (!CollectionUtils.isEmpty(list)) {
                IPage<CommodityModel> page = null;
                if (null != pageNo && null != pageSize) {
                    page = new Page<CommodityModel>(pageNo, pageSize);
                } else {
                    page = new Page<>();
                }
                page.setRecords(list);
                pageResult.setResult(page);
            } else {
                pageResult.error500("数据为空");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            pageResult.error500("后台异常");
        }
        return pageResult;
    }

    @PostMapping(value = "/add")
    public Result<Object> saveCommodity(@RequestBody Commodity commodity) {
        Result<Object> result = new Result<>();
        try {
            boolean saveResult = commodityService.save(commodity);
            if (!saveResult) {
                result.error500("操作失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("后台异常");
        }
        return result;
    }

    @DeleteMapping(value = "/del")
    public Result<Object> deleteCommodity(String id) {
        Result<Object> result = new Result<>();
        try {
            boolean delResult = commodityService.deleteCommodityById(id);
            if (!delResult) {
                result.error500("操作失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("后台异常");
        }
        return result;
    }

}
